﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using System.Windows.Forms;

namespace Atentis_Connector
{
	public partial class MainForm : Form, XmlWork.IXmlWorker
	{
		#region Переменные
		private AtentisWrapper aWrap;
		private AtentisConnection aCon;

		private bool m_FILoaded = false;
		private bool m_AllTrdReplied = false;
		//Список торгуемых финансовых инструментов
		private List<WorkWithSec> m_TradedSecsList = new List<WorkWithSec>();
		private List<IStrategy> m_AwalibleStrategies;
		private Color m_DefColor;
		private string SergContrTrendStrategyNAME = SergContrTrendStrategy.StrategyName;
		#endregion Переменные

		#region Конструктор
		public MainForm()
		{
			InitializeComponent();

			m_AwalibleStrategies = new List<IStrategy>();

			AwalibleStrategiesComboBox.Items.Add(SergContrTrendStrategyNAME);
			AwalibleStrategiesComboBox.SelectedIndex = 0;

			m_DefColor = this.BackColor;

		}
		#endregion Конструктор

		#region Подключение
		private bool m_Connected = false;

		private void connectButton_Click(object sender, EventArgs e)
		{
			Connect();
		}

		private void Connect()
		{
			if (!this.m_Connected)
			{

				aWrap = new AtentisWrapper();
				aCon = (AtentisConnection)aWrap.AddConnection("DataSlot", serverTextBox.Text, loginTextBox.Text, passwordTextBox.Text);
				aCon.Connected += aCon_Connected;
				aCon.SecMaster.FILoaded += SecMaster_FILoaded;
				aCon.SecMaster.HasNewTrade += SecMaster_HasNewTrade;
				aCon.SecMaster.SellOrderComplete += SecMaster_SellOrderComplete;
				aCon.SecMaster.BuyOrderComplete += SecMaster_BuyOrderComplete;
				aCon.SecMaster.HoldingsUpdated += SecMaster_PositionsUpdated;
				aCon.SecMaster.AllTrdReplied += SecMaster_AllTrdReplied;

				OpenTables(aCon);

				aCon.Connect();
				aCon.RefreshFreq = 1;
				while (!m_FILoaded)
				{
					System.Threading.Thread.Sleep(10);
					Application.DoEvents();
				}
				m_Connected = true;
				this.connectButton.Text = "Отключить";
			}
			else
			{
				aCon.Disconnect();
				m_Connected = false;
				this.connectButton.Text = "Подключить";
			}
		}

		void SecMaster_AllTrdReplied(object sender, EventArgs e)
		{
			m_AllTrdReplied = true;
		}


		void SecMaster_FILoaded(object sender, EventArgs e)
		{
			m_FILoaded = true;
		}

		private void aCon_Connected(object sender, EventArgs e)
		{
			var con = ((AtentisConnection)sender);
		}

		private void fiTimer_Tick(object sender, EventArgs e)
		{
			//if (m_FILoaded && aCon != null && aCon.WFirm_Holding_Total != null && aCon.WFirm_Holding_Total.Count() > 1)
			if (m_FILoaded && aCon != null && aCon.WSerurities != null && aCon.WSerurities.Count() > 1)
			{
				//var count = aCon.WFirm_Holding_Total.Count();
				var count = aCon.WSerurities.Count();
				for (int i = 0; i < count; i++)
				{
					//var elem = aCon.WFirm_Holding_Total[i];
					var elem = aCon.WSerurities[i];
					if (elem != null) this.fiComboBox.Items.Add(elem.SecCode);
				}
				this.fiComboBox.SelectedIndex = 1;

				this.fiTimer.Stop();
				this.fiTimer.Enabled = false;
			}
		}

		#endregion Подключение

		#region События об исполнении
		void SecMaster_SellOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var p = e as AtentisConnectorEventArgs;
				var newRow = p.WrapeTradesRow;
				var sec = m_TradedSecsList.Find(x => x.SecCode == newRow.SecCode);
				if (sec != null)
				{
					sec.ProcessSellTrade(newRow);
					ResetForm();
				}
			}
		}

		void SecMaster_BuyOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var p = e as AtentisConnectorEventArgs;
				var newRow = p.WrapeTradesRow;
				var sec = m_TradedSecsList.Find(x => x.SecCode == newRow.SecCode);
				if (sec != null)
				{
					sec.ProcessBuyTrade(newRow);
					ResetForm();
				}
			}
		}
		#endregion События об исполнении

		#region События об обновлении позиций
		void SecMaster_PositionsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var p = e as AtentisConnectorEventArgs;
				var newRow = p.WrapperHoldings;
				var sec = m_TradedSecsList.Find(x => x.SecCode == newRow.SecCode);
				if (sec != null)
					sec.ProcessPositions(newRow);
			}
		}
		#endregion События об обновлении позиций

		#region События о получении новой сделки
		void SecMaster_HasNewTrade(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var p = e as AtentisConnectorEventArgs;
				var newRow = p.AllTradesRow;
				ProcessNewTrade(newRow);
			}
		}

		private void ProcessNewTrade(WrapperAll_Trades newRow)
		{
			var sec = TryGetSelectedSecurity(newRow.SecCode);
			if (sec != null)
			{
				var candleList = sec.CandleList;
				if (candleList != null)
				{
					//newRow.SecCode = string.Empty;
					candleList.AddTick(newRow);
				}
			}
		}
		#endregion События о получении новой сделки

		#region Работа с таблицами
		private static void OpenTables(AtentisConnection con)
		{

			con.OpenTable(WrapperEnums.AllTables.atSECURITIES, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atINDEXES, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atBOARDS, "", "");
			con.OpenTable(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atHISTORY, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atHISTORY_DAILY, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atNEWS, "", "");

			con.OpenTable(WrapperEnums.AllTables.atORDERS, "", "");
			con.OpenTable(WrapperEnums.AllTables.atPOSITIONS, "", "");
			con.OpenTable(WrapperEnums.AllTables.atSTOPORDERS, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atTESYSTIME, "", "");
			con.OpenTable(WrapperEnums.AllTables.atTRADES, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atTRDACC, "", "");
			con.OpenTable(WrapperEnums.AllTables.atALL_TRADES, "", "");

		}
		#endregion Работа с таблицами

		#region События формы
		private void SaveInBDCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			aCon.SecMaster.SaveInDB = SaveInBDCheckBox.Checked;
		}

		private void UseThisFIButton_Click(object sender, EventArgs e)
		{
			string selectedSecCode = this.fiComboBox.Text;

			AddTradeSecurity(selectedSecCode);
		}

		private void AddTradeSecurity(string secCode)
		{
			if (aCon != null && aCon.SecMaster != null)
			{
				//Ищем нужный нам инструмент
				WrapperSecurities sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
				while (sec == null)
				{
					sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
					System.Threading.Thread.Sleep(10);
				}
				//Добавляем его в список инструментов по которым строятся свечи
				if (!aCon.SecMaster.SecForCandlesDict.Keys.Contains(sec.SecCode))
				{
					TradedFIListBox.Items.Add(sec.SecCode);
					aCon.SecMaster.SecForCandlesDict.Add(sec.SecCode, sec.SecBoard);
					m_TradedSecsList.Add(new WorkWithSec(sec.SecCode));
				}
			}
		}

		private void AddStrategyButton_Click(object sender, EventArgs e)
		{
			foreach (var strategyName in AwalibleStrategiesComboBox.Items)
			{
				if (((string)strategyName).Equals(AwalibleStrategiesComboBox.Text))
				{
					var sec = TryGetSelectedSecurity();
					if (sec != null)
					{
						AddSecurityStrategy(strategyName, sec);
						var strategy = sec.Strategies.Find(x => x.StrategyName.Equals(strategyName));
						SetCandleListToSecurity(strategy.StrategySettings.Period, strategy, sec);
						ShowFIStrategies(sec);
					}
				}
			}
		}

		private void TradedFIListBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			var sec = TryGetSelectedSecurity();
			if (sec != null)
			{
				ShowFIStrategies(sec);
				startStopButton.Enabled = true;
				moneyControlButton.Enabled = true;
			}
			else
			{
				startStopButton.Enabled = false;
				moneyControlButton.Enabled = false;
			}
		}

		private void moneyControlButton_Click(object sender, EventArgs e)
		{
			//-------------
			var sec = TryGetSelectedSecurity();
			MoneyControl mc = null;
			if (sec != null)
			{
				if (sec.MoneyControl!= null)
				{
					mc = new MoneyControl();
					mc.SecCode = sec.SecCode;
					mc.p_DeltaProfit = sec.MoneyControl.p_DeltaProfit;
					mc.p_DeltaProfitLine = sec.MoneyControl.p_DeltaProfitLine;
					mc.p_Loss = sec.MoneyControl.p_Loss;
					mc.p_Profit = sec.MoneyControl.p_Profit;
					mc.p_ReturnSlide = sec.MoneyControl.p_ReturnSlide;
					mc.p_StepCount = sec.MoneyControl.p_StepCount;
					mc.p_StepDelta = sec.MoneyControl.p_StepDelta;
					mc.p_StepVolume = sec.MoneyControl.p_StepVolume;
					mc.p_Volume = sec.MoneyControl.p_Volume;
				}
			}
			//-------------
			MoneyControlForm mcForm;
			if (mc == null )
				mcForm = new MoneyControlForm();
			else
				mcForm = new MoneyControlForm(mc);

			mcForm.MoneyControlSettingsUpdated += mcForm_MoneyControlSettingsUpdated;
			mcForm.Show();
		}


		private void startStopButton_Click(object sender, EventArgs e)
		{
				var sec = TryGetSelectedSecurity();
				if (sec != null)
				{
					if (sec.IsStarted)
					{
						/*
						obj_Alor.e_BuyOrderComplete -= new Action<int, double>(obj_CC.F_NewBuyTrade);
						obj_Alor.e_SellOrderComplete -= new Action<int, double>(obj_CC.F_NewSellTrade);
						obj_Alor.e_Position -= new Action<int>(obj_CC.F_SetPosition);
						*/

						sec.BuyOrderComplete -= new Action<int, double>(sec.MoneyControl.F_NewBuyTrade);
						sec.SellOrderComplete -= new Action<int, double>(sec.MoneyControl.F_NewSellTrade);
						sec.PositionsUpdated -= new Action<int>(sec.MoneyControl.F_SetPosition);

						for (int i = 0; i < sec.Strategies.Count; i++)
						{
							var strategy = sec.Strategies[i];
							strategy.NeedBuy -= strategy_NeedBuy;
							strategy.NeedSell -= strategy_NeedSell;
							strategy.CloseBuy -= strategy_CloseBuy;
							strategy.CloseSell -= strategy_CloseSell;
						}

						sec.MoneyControl.e_AddToLog -= MoneyControl_e_AddToLog;
						//sec.MoneyControl.e_BuyMarket -= MoneyControl_e_BuyMarket;
						//sec.MoneyControl.e_SellMarket -= MoneyControl_e_SellMarket;
						sec.MoneyControl.e_BuyLimit -= MoneyControl_e_BuyLimit;
						sec.MoneyControl.e_SellLimit -= MoneyControl_e_SellLimit;
						sec.MoneyControl.e_KillOrder -= MoneyControl_e_KillOrder;
						sec.MoneyControl.e_KillAllOrders -= MoneyControl_e_KillAllOrders;

						startStopButton.Text = "Старт";
						this.BackColor = m_DefColor;
						sec.IsStarted = false;
					}
					else
					{
						//sec.MoneyControl.F_NewBuyTrade;
						//sec.MoneyControl.F_NewSellTrade;
						//sec.MoneyControl.F_SetPosition;

						//sec.BuyOrderComplete += new Action<int, double>(sec.MoneyControl.F_NewBuyTrade);
						//sec.SellOrderComplete += new Action<int, double>(sec.MoneyControl.F_NewSellTrade);
                        for (int i = 0; i < sec.Strategies.Count; i++)
                        {
                            var strategy = sec.Strategies[i];
                            sec.SellOrderComplete += new Action<int, double>(strategy.OnSellOrderComplete);
                        }
						sec.PositionsUpdated += new Action<int>(sec.MoneyControl.F_SetPosition);

						sec.MoneyControl.e_AddToLog += MoneyControl_e_AddToLog;
						//sec.MoneyControl.e_BuyMarket += MoneyControl_e_BuyMarket;
						//sec.MoneyControl.e_SellMarket += MoneyControl_e_SellMarket;
						sec.MoneyControl.e_BuyLimit += MoneyControl_e_BuyLimit;
						sec.MoneyControl.e_SellLimit += MoneyControl_e_SellLimit;
						sec.MoneyControl.e_KillOrder += MoneyControl_e_KillOrder;
						sec.MoneyControl.e_KillAllOrders += MoneyControl_e_KillAllOrders;

						for (int i = 0; i < sec.Strategies.Count; i++)
						{
							var strategy = sec.Strategies[i];
							strategy.NeedBuy += strategy_NeedBuy;
                            strategy.NeedSell += strategy_NeedSell;
							strategy.CloseBuy += strategy_CloseBuy;
							strategy.CloseSell += strategy_CloseSell;
						}

						startStopButton.Text = "Стоп";
						this.BackColor = Color.Yellow;
						sec.IsStarted = true;
					}
				}
		}

		void MoneyControl_e_AddToLog(string obj)
		{
			Console.WriteLine(obj);
		}

		private void ResetForm()
		{
			//
		}
		private void DrawSellForm()
		{
			this.SetPropertyThreadSafe(() => this.BackColor, Color.Red);
		}
		private void DrawBuyForm()
		{
			this.SetPropertyThreadSafe(() => this.BackColor, Color.Green);
		}


		private void strategySettingsButton_Click(object sender, EventArgs e)
		{
			var strategyName = (string)FIStrategiesListBox.SelectedItem;
			if (string.IsNullOrEmpty(strategyName)) return;
			if (FIStrategiesListBox.Items.Count > 0)
			{
				StrategySettings ss = null;
				//---------------------------------------------------------------------------------------
				var sec = TryGetSelectedSecurity();
				if (sec != null)
				{
					//Тут нужен код для отображения настроек.
					if (sec.StrategiesNames.Contains(strategyName))
					{
						var settings = sec.Strategies[sec.StrategiesNames.IndexOf(strategyName)].StrategySettings;
						var minCandle = settings.MinCandleSize;
						var period = settings.Period;
						var stoploss = settings.StopLoss;
						var take = settings.TakeProfit;
						var vol = settings.Vol;
						var threhold = settings.Threshold;
						var useAO = settings.UseAO;
						var useFPos = settings.UseFraqPosition;
						ss = new StrategySettings(vol, minCandle, take, period, threhold, stoploss, useAO, useFPos);
					}
				}

				//---------------------------------------------------------------------------------------
				StrategyParamsInputForm settingsForm;
				if (ss != null)
					settingsForm = new StrategyParamsInputForm(ss);
				else
					settingsForm = new StrategyParamsInputForm();

				settingsForm.StrategySettingsUpdated += settingsForm_StrategySettingsUpdated;
				settingsForm.Show();
			}
		}

		private WorkWithSec TryGetSelectedSecurity()
		{
			return m_TradedSecsList.Find(x => x.SecCode == (string)TradedFIListBox.SelectedItem);
		}

		private WorkWithSec TryGetSelectedSecurity(string secCode)
		{
			return m_TradedSecsList.Find(x => x.SecCode == secCode);
		}

		private void FIStrategiesListBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			var sec = TryGetSelectedSecurity();
			if (sec != null)
			{
				var strat = sec.Strategies.Find(x => x.StrategyName == (string)FIStrategiesListBox.SelectedItem);
				if (strat != null)
					strategySettingsButton.Enabled = true;
				else
					strategySettingsButton.Enabled = false;
			}
			else
			{
				strategySettingsButton.Enabled = false;
			}
		}

		private void paintTimer_Tick(object sender, EventArgs e)
		{
			if (m_TradedSecsList != null)
			{
				var sec = TryGetSelectedSecurity();
				if (sec != null)
				{
					if (!sec.IsStarted)
						this.BackColor = m_DefColor;
					else
						this.BackColor = Color.Yellow;
				}
			}
		}

		#region Удаление инструмента
		private void delSecContextMenu_Click(object sender, EventArgs e)
		{
			var sec = TryGetSelectedSecurity();
			if (sec == null) return;
			var ind = m_TradedSecsList.IndexOf(sec);
			if (ind >= 0)
				m_TradedSecsList.RemoveAt(ind);

			aCon.SecMaster.SecForCandlesDict.Remove(sec.SecCode);

			TradedFIListBox.Items.Remove(TradedFIListBox.SelectedItem);
		}

		private void TradedFIListBox_MouseDown(object sender, MouseEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Right)
			{
				delSecContextMenu.Show();
			}
		}
		#endregion Удаление инструмента

		#endregion События формы

		#region События свечей
		void m_CandleList_CandleAdded(Candle obj)
		{
			AddCandle(obj);
		}

		void m_CandleList_CandleEdited(Candle obj)
		{
			EditCandle(obj);
		}

		private void AddCandle(Candle candle)
		{
			if (candle == null) return;
			var sec = TryGetSelectedSecurity(candle.Ticker);
			if (sec != null)
			{
				for (int i = 0; i < sec.Strategies.Count; i++)
				{
					sec.Strategies[i].NewCandle(candle);
				}

			}

		}

		private void EditCandle(Candle candle)
		{
			var sec = TryGetSelectedSecurity(candle.Ticker);
			if (sec != null)
			{
				var cl = sec.CandleList;
				if (cl == null) return;

				for (int i = 0; i < sec.Strategies.Count; i++)
				{
					var trd = new WrapperTrades();
					trd.Price = candle.Close;
					sec.Strategies[i].NewTrade(trd);
				}
			}
		}
		#endregion События свечей

		#region Работа со стратегиями
		private void AddSecurityStrategy(object strategyName, WorkWithSec sec)
		{
			if (!sec.StrategiesNames.Contains((string)strategyName))
			{
				if (strategyName.Equals(SergContrTrendStrategyNAME))
				{
					var strategy = (SergContrTrendStrategy)SetStrategyForFI(sec.SecCode);
					sec.Strategies.Add(strategy);
				}
			}
		}

		private IStrategy SetStrategyForFI(string secCode)
		{
			var strategy = new SergContrTrendStrategy();

			strategy.SecCode = secCode;
			strategy.CloseStrategy += strategy_CloseStrategy;
			return strategy;
		}

		private void SetCandleListToSecurity(int period, IStrategy strat, WorkWithSec security)
		{
			if (strat == null) return;
			SergContrTrendStrategy strategy = strat as SergContrTrendStrategy;

			if (security.CandleList == null)
				security.CandleList = new CandleList();

			security.CandleList.CandleAdded -= m_CandleList_CandleAdded;
			security.CandleList.CandleChanged -= m_CandleList_CandleEdited;
			security.CandleList.Candles.Clear();

			security.CandleList.Period = period;

			foreach (var item in aCon.SecMaster.WAllTrades)
			{
				if (item.SecCode == security.SecCode)
					security.CandleList.AddTick(item);
			}
			/*
			for (int i = 0; i < aCon.SecMaster.WAllTrades.Count; i++)
			{
				var item = aCon.SecMaster.WAllTrades[i];
				if (item.SecCode == (string)TradedFIListBox.SelectedItem)
					security.CandleList.AddTick(item);
			}
			*/
			security.CandleList.CandleAdded += m_CandleList_CandleAdded;
			security.CandleList.CandleChanged += m_CandleList_CandleEdited;

			strategy.SetHistory(security.CandleList.Candles);
		}

		void strategy_CloseStrategy(object sender, EventArgs e)
		{
			var strategy = (IStrategy)sender;
			foreach (var sec in m_TradedSecsList)
			{
				if (sec.Strategies.Contains(strategy))
				{
					sec.Strategies.Remove(strategy);
					ShowFIStrategies(sec);
				}
			}
		}

		void settingsForm_StrategySettingsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var settings = e as AtentisConnectorEventArgs;
				var sec = TryGetSelectedSecurity();
				if (sec != null)
				{
					var strategyName = (string)FIStrategiesListBox.SelectedItem;

					if (sec.StrategiesNames.Contains(strategyName))
					{
						IStrategy curStrategy = sec.Strategies[sec.StrategiesNames.IndexOf(strategyName)];
						if (curStrategy.StrategyName.Equals(SergContrTrendStrategyNAME))
						{

							((SergContrTrendStrategy)curStrategy).RemoveThatStrategy();

							var strategy = (SergContrTrendStrategy)SetStrategyForFI(sec.SecCode);
							strategy.StrategySettings.MinCandleSize = settings.SecurityStrategySettings.MinCandleSize;
							strategy.StrategySettings.Period = settings.SecurityStrategySettings.Period;
							strategy.StrategySettings.StopLoss = settings.SecurityStrategySettings.StopLoss;
							strategy.StrategySettings.Vol = settings.SecurityStrategySettings.Vol;
							strategy.StrategySettings.TakeProfit = settings.SecurityStrategySettings.TakeProfit;
							strategy.StrategySettings.Threshold = settings.SecurityStrategySettings.Threshold;
							strategy.StrategySettings.UseAO = settings.SecurityStrategySettings.UseAO;
							strategy.StrategySettings.UseFraqPosition = settings.SecurityStrategySettings.UseFraqPosition;


							sec.Strategies.Add(strategy);
							ShowFIStrategies(sec);

							SetCandleListToSecurity(strategy.StrategySettings.Period, strategy, sec);

						}

						//-----------------------------------------------------

						/*
						for (int i = 0; i < aCon.SecMaster.WAllTrades.Count; i++)
						{
							var item = aCon.SecMaster.WAllTrades[i];
							if (item.SecCode == (string)TradedFIListBox.SelectedItem)
								x.AddTick(item);
						}

						sec.Strategies[sec.StrategiesNames.IndexOf((string)FIStrategiesListBox.SelectedItem)].SetHistory(x.Candles);
						*/
						//-----------------------------------------------------
					}
				}
			}
		}

		private void ShowFIStrategies(WorkWithSec sec)
		{
			this.FIStrategiesListBox.Items.Clear();
			foreach (var strat in sec.Strategies)
			{
				this.FIStrategiesListBox.Items.Add(strat.StrategyName);
				this.FIStrategiesListBox.Refresh();
			}
		}
		#endregion Работа со стратегиями

		#region Обработка событий стратегий
        void strategy_NeedBuy(object sender, AtentisConnectorEventArgs e)
		{
			/*
			string s = m_Profit.ToString();
			this.profitTextBox.SetPropertyThreadSafe(() => this.profitTextBox.Text, s);
			this.SetPropertyThreadSafe(() => this.BackColor, Color.Green);
			m_Profit -= ((SergContrTrendStrategy)sender).Price;
			*/
			var sec = TryGetSelectedSecurity(((SergContrTrendStrategy)sender).SecCode);
			if (sec != null && sec.IsStarted)
			{
                sec.MoneyControl.F_Buy(e.OrderInfo.Price);
				Console.WriteLine(string.Format("Покупка {0} по {1}", sec.SecCode, ((SergContrTrendStrategy)sender).Price));
			}
		}

		void strategy_NeedSell(object sender, AtentisConnectorEventArgs e)
		{
			/*
			string s = m_Profit.ToString();
			this.profitTextBox.SetPropertyThreadSafe(() => this.profitTextBox.Text, s);
			this.SetPropertyThreadSafe(() => this.BackColor, Color.Red);
			m_Profit -= ((SergContrTrendStrategy)sender).Price;
			*/
			var sec = TryGetSelectedSecurity(((SergContrTrendStrategy)sender).SecCode);
			if (sec != null && sec.IsStarted)
			{
                sec.MoneyControl.F_Sell(e.OrderInfo.Price);
                //MoneyControl_e_SellLimit(sec.SecCode, 1, e.OrderInfo.Price);
				Console.WriteLine(string.Format("Продажа {0} по {1}", sec.SecCode, e.OrderInfo.Price));
			}
		}

        void strategy_CloseBuy(object sender, AtentisConnectorEventArgs e)
		{
			var sec = TryGetSelectedSecurity(((SergContrTrendStrategy)sender).SecCode);
			if (sec != null)
			{
				// Нужен код для закрытия покупки
                sec.MoneyControl.F_Sell(e.OrderInfo.Price);
				Console.WriteLine("Закрываем покупку");
			}
		}

        void strategy_CloseSell(object sender, AtentisConnectorEventArgs e)
		{
			var sec = TryGetSelectedSecurity(((SergContrTrendStrategy)sender).SecCode);
			if (sec != null)
			{
				// Нужен код для закрытия продажи
                sec.MoneyControl.F_Buy(e.OrderInfo.Price);
				Console.WriteLine("Закрываем продажу");
			}
		}
		#endregion Обработка событий стратегий

		#region Обработка событий контроля капитала
		void mcForm_MoneyControlSettingsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var settings = e as AtentisConnectorEventArgs;
				var mc = settings.MoneyControl;

				var sec = TryGetSelectedSecurity();
				if (sec != null)
				{
					//Тут нужен код для отображения настроек контроля капитала.
					sec.MoneyControl.F_SetSettings(
					mc.p_Profit,
					mc.p_Loss,
					mc.p_DeltaProfitLine,
					mc.p_DeltaProfit,
					mc.p_ReturnSlide,
					mc.p_Volume,
					mc.p_StepVolume,
					mc.p_StepCount,
					mc.p_StepDelta
					);
				}
			}
		}

		void MoneyControl_e_KillAllOrders()
		{
			// Тут Снимаем все заявки
			foreach (var order in aCon.SecMaster.WOrders)
			{
				if (order.Status == "A" || order.Status == "O")
				{
					aCon.DelOrder(order.OrderNo);
					ResetForm();
				}
			}
			Console.WriteLine("Снимаем все заявки");
		}

		void MoneyControl_e_KillOrder(long orderNo)
		{
			// Тут снимаем один ордер по его номеру
			if (aCon != null && aCon.SecMaster != null && aCon.SecMaster.WOrders != null)
			{
				var order = aCon.SecMaster.WOrders.Find(x => x.OrderNo == orderNo);
				if (order != null && order.OrderNo == orderNo && (order.Status == "A" || order.Status == "O"))
				{
					aCon.DelOrder(order.OrderNo);
					Console.WriteLine("Снимаем заявку {0}", order.OrderNo);
					ResetForm();
				}
			}
		}

		void MoneyControl_e_SellLimit(string secCode, int vol, double price)
		{
			// Тут продаем лимитно объем vol по цене price
			if (aCon != null && aCon.SecMaster != null)
			{
				//Ищем нужный нам инструмент
				WrapperSecurities sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
				
				if (sec != null)
				{
					string secBoard = sec.SecBoard;
					long outOrderNo = 0;
					string outResMsg = "";
					aCon.AddOrder("S", "L", "S", " ", "P", " ", secBoard, secCode, "", price, vol, "", out outOrderNo, out outResMsg);
					Console.WriteLine("Добавили заявку {0} на продажу лимитно объемом {1}, результат: {2}", outOrderNo, vol, outResMsg);
					DrawSellForm();
				}
			}
		}

		void MoneyControl_e_BuyLimit(string secCode, int vol, double price)
		{
			// Тут покупаем лимитно объем vol по цене price
			if (aCon != null && aCon.SecMaster != null)
			{
				//Ищем нужный нам инструмент
				WrapperSecurities sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
				
				if (sec != null)
				{
					string secBoard = sec.SecBoard;
					long outOrderNo = 0;
					string outResMsg = "";
					aCon.AddOrder("B", "L", "S", " ", "P", " ", secBoard, secCode, "", price, vol, "", out outOrderNo, out outResMsg);
					Console.WriteLine("Добавили заявку {0} на покупку лимитно объемом {1}, результат: {2}", outOrderNo, vol, outResMsg);
					DrawBuyForm();
				}
			}
		}

		void MoneyControl_e_SellMarket(string secCode, int vol)
		{
			// Продать по-рынку объем vol
			if (aCon != null && aCon.SecMaster != null)
			{
				//Ищем нужный нам инструмент
				WrapperSecurities sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
				
				if (sec != null)
				{
					string secBoard = sec.SecBoard;
					long outOrderNo = 0;
					string outResMsg = "";
					aCon.AddOrder("S", "M", "S", " ", "P", " ", secBoard, secCode, "", 0, vol, "", out outOrderNo, out outResMsg);
					Console.WriteLine("Добавили заявку {0} на продажу объемом {1}, результат: {2}", outOrderNo, vol, outResMsg);
					DrawSellForm();
				}
			}
		}

		void MoneyControl_e_BuyMarket(string secCode, int vol)
		{
			// Купить по-рынку объем vol
			if (aCon != null && aCon.SecMaster != null)
			{
				//Ищем нужный нам инструмент
				WrapperSecurities sec = aCon.WSerurities.Find(x => x.SecCode == secCode);
				
				if (sec != null)
				{
					string secBoard = sec.SecBoard;
					long outOrderNo = 0;
					string outResMsg = "";
					aCon.AddOrder("B", "M", "S", " ", "P", " ", secBoard, secCode, "", 0, vol, "", out outOrderNo, out outResMsg);
					Console.WriteLine("Добавили заявку {0} на покупку объемом {1}, результат: {2}", outOrderNo, vol, outResMsg);
					DrawBuyForm();
				}
			}
		}
		#endregion Обработка событий контроля капитала

		#region Сохранение и загрузка настроек
		public string ObjectName
		{
			get { return "Atentis_Bot"; }
		}

		public void SaveToFile(ref System.Xml.XmlTextWriter xmlOut)
		{
			xmlOut.WriteStartElement(XmlWork.WorkWithXML.SRT_MAINWINDOWCONFIG);
			xmlOut.WriteAttributeString("Login", loginTextBox.Text);
			xmlOut.WriteAttributeString("Password", passwordTextBox.Text);
			xmlOut.WriteAttributeString("Server", serverTextBox.Text);
			xmlOut.WriteAttributeString("Port", portTextBox.Text);
			xmlOut.WriteAttributeString("SaveInDB", SaveInBDCheckBox.Checked.ToString());
			xmlOut.WriteEndElement();

			foreach (var sec in m_TradedSecsList)
			{
				foreach (var strat in sec.Strategies)
				{
					xmlOut.WriteStartElement(ObjectName);

					xmlOut.WriteAttributeString("TradedFI", sec.SecCode);

					xmlOut.WriteAttributeString("DeltaProfit", sec.MoneyControl.p_DeltaProfit.ToString());
					xmlOut.WriteAttributeString("DeltaProfitLine", sec.MoneyControl.p_DeltaProfitLine.ToString());
					xmlOut.WriteAttributeString("Loss", sec.MoneyControl.p_Loss.ToString());
					xmlOut.WriteAttributeString("Profit", sec.MoneyControl.p_Profit.ToString());
					xmlOut.WriteAttributeString("ReturnSlide", sec.MoneyControl.p_ReturnSlide.ToString());
					xmlOut.WriteAttributeString("StepCount", sec.MoneyControl.p_StepCount.ToString());
					xmlOut.WriteAttributeString("StepDelta", sec.MoneyControl.p_StepDelta.ToString());
					xmlOut.WriteAttributeString("StepVolume", sec.MoneyControl.p_StepVolume.ToString());
					xmlOut.WriteAttributeString("Volume", sec.MoneyControl.p_Volume.ToString());

					xmlOut.WriteAttributeString("StrategyName", strat.StrategyName);
					xmlOut.WriteAttributeString("StrategyPeriod", strat.StrategySettings.Period.ToString());
					xmlOut.WriteAttributeString("StrategyStopLoss", strat.StrategySettings.StopLoss.ToString());
					xmlOut.WriteAttributeString("StrategyTakeProfit", strat.StrategySettings.TakeProfit.ToString());
					xmlOut.WriteAttributeString("StrategyVol", strat.StrategySettings.Vol.ToString());
					xmlOut.WriteAttributeString("StrategyMinCandle", strat.StrategySettings.MinCandleSize.ToString());
					xmlOut.WriteAttributeString("StrategyThreshold", strat.StrategySettings.Threshold.ToString());
					xmlOut.WriteAttributeString("StrategyUseAO", strat.StrategySettings.UseAO.ToString());
					xmlOut.WriteAttributeString("StrategyUseFraqPosition", strat.StrategySettings.UseFraqPosition.ToString());

				}

				xmlOut.WriteEndElement();
			}
		}

		public void ReadFromFile(System.Xml.XmlTextReader xmlIn)
		{
			try
			{
				if (xmlIn.Name == XmlWork.WorkWithXML.SRT_MAINWINDOWCONFIG)
				{
					loginTextBox.Text = Convert.ToString(xmlIn.GetAttribute("Login"));
					passwordTextBox.Text = Convert.ToString(xmlIn.GetAttribute("Password"));
					serverTextBox.Text = Convert.ToString(xmlIn.GetAttribute("Server"));
					portTextBox.Text = Convert.ToString(xmlIn.GetAttribute("Port"));
					SaveInBDCheckBox.Checked = Convert.ToBoolean(xmlIn.GetAttribute("SaveInDB"));
					TradedFIListBox.Items.Clear();
					Connect();
				}
				if (xmlIn.Name == ObjectName)
				{
					string secCode = Convert.ToString(xmlIn.GetAttribute("TradedFI"));
					string strategyName = Convert.ToString(xmlIn.GetAttribute("StrategyName"));


					// Получаем инструмент, если уже добавлен.
					if (!TradedFIListBox.Items.Contains(secCode))
						AddTradeSecurity(secCode);
					
					var sec = TryGetSelectedSecurity(secCode);
					if (sec != null)
					{
						AddSecurityStrategy(strategyName, sec);
						var strategy = sec.Strategies.Find(x => x.StrategyName.Equals(strategyName));
						var strategySettings = strategy.StrategySettings;
						strategySettings.Period = Convert.ToInt32(xmlIn.GetAttribute("StrategyPeriod"));
						strategySettings.StopLoss = Convert.ToDecimal(xmlIn.GetAttribute("StrategyStopLoss"));
						strategySettings.Vol = Convert.ToInt32(xmlIn.GetAttribute("StrategyVol"));
						strategySettings.MinCandleSize = Convert.ToInt32(xmlIn.GetAttribute("StrategyMinCandle"));
						strategySettings.TakeProfit = Convert.ToDecimal(xmlIn.GetAttribute("StrategyTakeProfit"));
						strategySettings.Threshold = Convert.ToDecimal(xmlIn.GetAttribute("StrategyThreshold"));
						strategySettings.UseAO = Convert.ToBoolean(xmlIn.GetAttribute("StrategyUseAO"));
						strategySettings.UseFraqPosition = Convert.ToBoolean(xmlIn.GetAttribute("StrategyUseFraqPosition"));

						SetCandleListToSecurity(strategySettings.Period, strategy, sec);
						ShowFIStrategies(sec);

						// Подгружаем настройки контроля капитала для инструмента
						MoneyControl mc = new MoneyControl();
						mc.SecCode = sec.SecCode;
						mc.p_DeltaProfit = Convert.ToInt32(xmlIn.GetAttribute("DeltaProfit"));
						mc.p_DeltaProfitLine = Convert.ToInt32(xmlIn.GetAttribute("DeltaProfitLine"));
						mc.p_Loss = Convert.ToInt32(xmlIn.GetAttribute("Loss"));
						mc.p_Profit = Convert.ToInt32(xmlIn.GetAttribute("Profit"));
						mc.p_ReturnSlide = Convert.ToInt32(xmlIn.GetAttribute("ReturnSlide"));
						mc.p_StepCount = Convert.ToInt32(xmlIn.GetAttribute("StepCount"));
						mc.p_StepDelta = Convert.ToInt32(xmlIn.GetAttribute("StepDelta"));
						mc.p_StepVolume = Convert.ToInt32(xmlIn.GetAttribute("StepVolume"));
						mc.p_Volume = Convert.ToInt32(xmlIn.GetAttribute("Volume"));

						sec.MoneyControl = mc;
					}

				}
			}
			catch (Exception)
			{ }
		}

		private const string CONFIG_FILENAME = "BotConfig.xml";

		private void MainForm_Load(object sender, EventArgs e)
		{
			if (System.IO.File.Exists(CONFIG_FILENAME))
			{
				var obj = this as XmlWork.IXmlWorker;
				XmlWork.WorkWithXML.ReadFromXmlFile(CONFIG_FILENAME, ObjectName, ref obj);
			}
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			var obj = this as XmlWork.IXmlWorker;
			XmlWork.WorkWithXML.SaveToXmlFile(CONFIG_FILENAME, ref obj);
		}

		#endregion Сохранение и загрузка настроек

	}
}
